package com.wenqiner.requesttool.view.base;

import com.alibaba.fastjson2.JSON;
import com.wenqiner.requesttool.core.business.lingyin.ParamData;
import com.wenqiner.requesttool.domain.HttpResponseData;
import com.wenqiner.requesttool.util.AESEncryptUtil;
import com.wenqiner.requesttool.util.CommonUtil;
import com.wenqiner.requesttool.util.RSAUtil;

/**
 * @author rhf
 * @date 2023-03-28
 **/
public interface InnerParamProcess {
    /**
     * 请求加密
     *
     * @param publicKey 公钥
     * @param param     参数
     * @return java.lang.String
     * @author rhf
     */
    default String requestEncrypt(String publicKey, String param) throws Exception {
        String random = CommonUtil.getValue();
        String code = RSAUtil.encryptByPublicKey(publicKey, random);
        String data = AESEncryptUtil.encryptBase64(param, random);
        ParamData<?> paramData = new ParamData<>();
        paramData.setEncryptedData(data);
        paramData.setSecretCode(code);
        return CommonUtil.formatJson(paramData);
    }

    /**
     * 解密验签
     *
     * @param publicKey        公钥
     * @param httpResponseData 响应
     * @return com.wenqiner.requesttool.core.business.lingyin.ParamData
     * @author rhf
     */
    default ParamData<String> responseDecrypt(String publicKey, HttpResponseData<String> httpResponseData) throws Exception {
        ParamData res = JSON.parseObject(httpResponseData.getData(), ParamData.class);
        if (res.isSuccess()) {
            String code = RSAUtil.decryptByPublicKey(publicKey, res.getSecretCode());
            String data = AESEncryptUtil.decryptBase64(res.getEncryptedData(), code);
            res.setData(data);
        }
        return res;
    }
}
